<template>
  <ion-page>
    <ion-header>
      <ion-toolbar>
        <ion-title>选择角色</ion-title>
        <ion-buttons slot="end">
          <ion-button @click="handleLogout" fill="clear">
            <ion-icon :icon="logOutOutline"></ion-icon>
            退出
          </ion-button>
        </ion-buttons>
      </ion-toolbar>
    </ion-header>

    <ion-content :fullscreen="true" class="ion-padding">
      <div class="role-select-container">
        <!-- 用户信息 -->
        <div class="user-info">
          <ion-avatar>
            <ion-icon :icon="personCircleOutline" size="large"></ion-icon>
          </ion-avatar>
          <h2>{{ userStore.user?.name }}</h2>
          <p v-if="isNewUser">欢迎加入！请选择您的角色</p>
          <p v-else>请选择您要使用的角色</p>
        </div>

        <!-- 角色列表 -->
        <div class="roles-container" v-if="!loading">
          <div
            v-for="role in allRoles"
            :key="role.key"
            class="role-item"
            @click="toggleRole(role.key)"
            :class="{
              'selected': isRoleSelected(role.key),
              'available': isRoleAvailable(),
              'disabled': !isRoleAvailable()
            }"
          >
            <div class="role-content">
              <div class="role-header">
                <div class="role-icon">
                  <ion-icon :icon="getRoleIcon(role.key)" size="large" :color="getRoleColor(role.key)"></ion-icon>
                </div>
                <div class="role-info">
                  <h3>{{ role.definition.name }}</h3>
                  <p>{{ role.definition.description }}</p>
                </div>
                <div class="role-selector">
                  <ion-radio
                    :value="role.key"
                    :checked="isRoleSelected(role.key)"
                    :disabled="!isRoleAvailable()"
                    @click.stop="toggleRole(role.key)"
                  ></ion-radio>
                </div>
              </div>
              <div class="permissions">
                <ion-chip
                  v-for="permission in role.definition.permissions.slice(0, 3)"
                  :key="permission"
                  size="small"
                  :color="getRoleColor(role.key)"
                  outline
                >
                  {{ getPermissionName(permission) }}
                </ion-chip>
                <ion-chip
                  v-if="role.definition.permissions.length > 3"
                  size="small"
                  color="medium"
                  outline
                >
                  +{{ role.definition.permissions.length - 3 }}
                </ion-chip>
              </div>
            </div>
          </div>
        </div>

        <!-- 加载状态 -->
        <div v-if="loading" class="loading-container">
          <ion-spinner name="crescent"></ion-spinner>
          <p>加载角色信息中...</p>
        </div>

        <!-- 确认按钮 -->
        <ion-button
          expand="block"
          :disabled="!canConfirm || confirming"
          @click="confirmRole"
          class="confirm-button"
        >
          <ion-spinner v-if="confirming" name="crescent"></ion-spinner>
          <span v-else>完成注册</span>
        </ion-button>

        <!-- 用户提示 -->
        <div class="user-hint">
          <ion-note color="medium">
            <ion-icon :icon="informationCircleOutline"></ion-icon>
            请选择一个角色，设置后不可更改
          </ion-note>
        </div>
      </div>
    </ion-content>
  </ion-page>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import {
  IonPage,
  IonHeader,
  IonToolbar,
  IonTitle,
  IonContent,
  IonButtons,
  IonButton,
  IonIcon,
  IonAvatar,
  IonChip,
  IonSpinner,
  IonRadio,
  IonNote,
  alertController,
  toastController
} from '@ionic/vue'
import {
  personCircleOutline,
  logOutOutline,
  shieldCheckmarkOutline,
  homeOutline,
  peopleOutline,
  informationCircleOutline
} from 'ionicons/icons'
import { useUserStore } from '@/stores/user'
import { getRoles, selectUserRoles, type RoleDefinition } from '@/api/auth'

const router = useRouter()
const userStore = useUserStore()

const loading = ref(true)
const confirming = ref(false)
const selectedRoles = ref<string[]>([])
const roleDefinitions = ref<Record<string, RoleDefinition>>({})

// 是否为新用户（未设置过角色）
const isNewUser = computed(() => {
  return !userStore.user?.hasSetRoles
})

// 所有可用角色
const allRoles = computed(() => {
  return Object.keys(roleDefinitions.value)
    .filter(roleKey => roleKey !== 'admin') // 普通用户不能选择管理员角色
    .map(roleKey => ({
      key: roleKey,
      definition: roleDefinitions.value[roleKey] || {
        name: roleKey,
        description: '角色描述',
        permissions: []
      }
    }))
})

// 是否可以确认
const canConfirm = computed(() => {
  return selectedRoles.value.length === 1
})

// 获取角色图标
const getRoleIcon = (role: string) => {
  const icons: Record<string, any> = {
    admin: shieldCheckmarkOutline,
    landlord: homeOutline,
    tenant: peopleOutline
  }
  return icons[role] || personCircleOutline
}

// 获取角色颜色
const getRoleColor = (role: string) => {
  const colors: Record<string, string> = {
    admin: 'danger',
    landlord: 'warning',
    tenant: 'primary'
  }
  return colors[role] || 'medium'
}

// 获取权限名称
const getPermissionName = (permission: string) => {
  const names: Record<string, string> = {
    manage_users: '用户管理',
    manage_properties: '房源管理',
    manage_rentals: '租赁管理',
    view_reports: '报表查看',
    manage_tenants: '租客管理',
    search_properties: '房源搜索',
    view_profile: '个人资料',
    view_rentals: '查看租赁'
  }
  return names[permission] || permission
}

// 检查角色是否被选中
const isRoleSelected = (role: string) => {
  return selectedRoles.value.includes(role)
}

// 检查角色是否可用（新用户可以选择任何角色）
const isRoleAvailable = () => {
  return true
}

// 切换角色选择（单选模式）
const toggleRole = (role: string) => {
  if (!isRoleAvailable()) return

  // 单选模式：直接设置选中的角色
  selectedRoles.value = [role]
}

// 确认角色选择
const confirmRole = async () => {
  if (!canConfirm.value) return

  confirming.value = true

  try {
    const selectedRole = selectedRoles.value[0]

    // 只允许新用户设置角色，已设置角色的用户不能再次选择
    if (!isNewUser.value) {
      throw new Error('角色已设置，不能重复设置')
    }

    // 新用户：保存选择的角色到后端
    if (!userStore.user?.id) {
      throw new Error('用户信息不完整')
    }

    try {
      const response = await selectUserRoles(userStore.user.id, [selectedRole])

      if (response.data) {
        // 更新用户信息
        userStore.setUser(response.data)

        // 设置当前角色
        userStore.setCurrentRole(selectedRole)

        // 显示成功提示
        const toast = await toastController.create({
          message: '角色设置成功！欢迎使用租房系统',
          duration: 3000,
          color: 'success',
          position: 'top'
        })
        await toast.present()
      } else {
        throw new Error('角色设置失败')
      }
    } catch (apiError: any) {
      throw new Error(apiError.message || '角色设置失败')
    }

    // 跳转到主页
    router.replace('/tabs/home')
  } catch (error: any) {
    console.error('角色操作失败:', error)

    const alert = await alertController.create({
      header: '操作失败',
      message: error.message || '角色操作失败，请重试',
      buttons: ['确定']
    })
    await alert.present()
  } finally {
    confirming.value = false
  }
}

// 退出登录
const handleLogout = async () => {
  const alert = await alertController.create({
    header: '确认退出',
    message: '确定要退出登录吗？',
    buttons: [
      {
        text: '取消',
        role: 'cancel'
      },
      {
        text: '确定',
        handler: () => {
          userStore.logout()
          router.replace('/login')
        }
      }
    ]
  })
  await alert.present()
}

// 加载角色定义
const loadRoles = async () => {
  try {
    const response = await getRoles()
    if (response.success) {
      roleDefinitions.value = response.data
    }
  } catch (error) {
    console.error('加载角色失败:', error)
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 检查登录状态
  if (!userStore.isLoggedIn) {
    router.replace('/login')
    return
  }

  // 检查是否已设置角色（已设置角色的用户不能再次选择）
  if (userStore.user?.hasSetRoles) {
    router.replace('/home')
    return
  }

  // 新用户不需要初始化角色选择

  loadRoles()
})
</script>

<style scoped>
.role-select-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
}

.user-info {
  text-align: center;
  margin-bottom: 30px;
  padding: 20px 0;
}

.user-info ion-avatar {
  width: 80px;
  height: 80px;
  margin: 0 auto 16px auto;
}

.user-info h2 {
  margin: 0 0 8px 0;
  color: var(--ion-color-dark);
}

.user-info p {
  color: var(--ion-color-medium);
  margin: 0;
}

.roles-container {
  display: flex;
  flex-direction: column;
  gap: 12px;
  margin-bottom: 30px;
}

.role-item {
  background: white;
  border-radius: 12px;
  border: 2px solid var(--ion-color-light);
  cursor: pointer;
  transition: all 0.3s ease;
  overflow: hidden;
}

.role-item:hover:not(.disabled) {
  border-color: var(--ion-color-primary);
  background: rgba(var(--ion-color-primary-rgb), 0.04);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.role-item.selected {
  border-color: var(--ion-color-primary);
  background: rgba(var(--ion-color-primary-rgb), 0.08);
}

.role-item.disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.role-content {
  padding: 16px;
}

.role-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.role-icon {
  flex-shrink: 0;
  width: 48px;
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(var(--ion-color-primary-rgb), 0.1);
  border-radius: 50%;
  transition: background-color 0.3s ease;
}

.role-item.selected .role-icon {
  background: rgba(var(--ion-color-primary-rgb), 0.2);
}

.role-info {
  flex: 1;
}

.role-info h3 {
  margin: 0 0 4px 0;
  color: var(--ion-color-dark);
  font-size: 18px;
  font-weight: 600;
}

.role-info p {
  margin: 0;
  color: var(--ion-color-medium);
  font-size: 14px;
  line-height: 1.4;
}

.role-selector {
  flex-shrink: 0;
}

.permissions {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
}

.loading-container {
  text-align: center;
  padding: 40px 20px;
}

.loading-container p {
  margin-top: 16px;
  color: var(--ion-color-medium);
}

.confirm-button {
  height: 48px;
  margin-top: 20px;
}

.user-hint {
  margin-top: 16px;
  text-align: center;
}

.user-hint ion-note {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  font-size: 14px;
}
</style>
